package sz.szsmk.citizencard.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.util.Base64;
import android.view.View;
import android.widget.Toast;

import com.chenenyu.router.annotation.Route;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.FaceAuthActivityBinding;
import sz.szsmk.citizencard.dialog.OneButtonProDialog;
import sz.szsmk.citizencard.dialog.SuccessDialog;
import sz.szsmk.citizencard.face.BottomButtonFragment;
import sz.szsmk.citizencard.face.ResultFragment;
import sz.szsmk.citizencard.face.StartPageFragment;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.GetOrderOpenidRes;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.mvp.contract.IFaceAuthContract;
import sz.szsmk.citizencard.mvp.presenter.FaceAuthPresenter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;

/**
 * Copyright (c)2019
 * author: zdh
 * created on: 2019/1/8 10:58
 * description:
 */
@Route("FaceAuthActivity")
public class FaceAuthActivity extends IBaseActivity<FaceAuthPresenter, FaceAuthActivityBinding>
        implements IFaceAuthContract.IFaceAuthView, View.OnClickListener {

    public static final String EXTRA_RESULT_CODE = "extra_result_code";

    public static final int STATE_START = 0;
    public static final int STATE_RESULT = 1;

    private StartPageFragment mStartPageFragment = null;
    private BottomButtonFragment mBottomButtonFragment = null;
    private ResultFragment mResultFragment = null;
    private String idCard;
    private String custName;
    private Dialog dialog;
    private static final int TAKE_PHOTO_REQUEST_CODE = 1;
    private int intoType = 0;
    private String chooseType = "";
    private String access_token;

    @Override
    protected int attachLayoutRes() {
        return R.layout.face_auth_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        access_token = ACache.get(this).getAsString("access_token");
        dataBinding.faceStart.setOnClickListener(this);
        switchFragment(STATE_START, getIntent());
        idCard = getIntent().getStringExtra(Constant.ID_CARD);
        intoType = getIntent().getIntExtra("intotype", 0);
        chooseType = getIntent().getStringExtra("choosetype");
        custName = getIntent().getStringExtra(Constant.CUST_NAME);
        dataBinding.faceName.setText(custName);
        dataBinding.titleLayout.settingTitle.setText("实名认证");

    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void faceResultSucc(BaseBean response) {
        dismissLoadingDialog();
        OneButtonProDialog passwordDialog = new OneButtonProDialog();
        passwordDialog.setAction(1);
        passwordDialog.setContent("人脸识别已通过");
        passwordDialog.setTitle("苏州市民卡");
        passwordDialog.setCancelText("我知道了");
        passwordDialog.setOnCancelClickListener(new OneButtonProDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                if (intoType == 1) {
                    if ("ghf".equals(chooseType)) {
                        mPresenter.getGetOrderId();

                    } else if ("gjj".equals(chooseType)) {
                        String url = Constant.BASE_URL + "app-front-end/#/fund/main?access_token=" + access_token;
                        Bundle bundle = new Bundle();
                        bundle.putString("url", url);
                        RealNameActivity.mBActivity.finish();
                        JumpUtils.jumptoNatvie(FaceAuthActivity.this, "webView", 0, bundle);
                    } else if ("sb".equals(chooseType)) {

                        String url = Constant.BASE_URL + "app-front-end/#/fundAndSociety/authPage?access_token=" + access_token + "&type=1&name=" + custName;
                        Bundle bundle = new Bundle();
                        bundle.putString("url", url);
                        RealNameActivity.mBActivity.finish();
                        JumpUtils.jumptoNatvie(FaceAuthActivity.this, "webView", 0, bundle);
                    }
                }

                finish();
//                Toast.makeText(BankAdminActivity.this, "取消", Toast.LENGTH_SHORT).show();
            }
        });
        passwordDialog.setOnOkClickListener(new OneButtonProDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {

//                Toast.makeText(BankAdminActivity.this, "开启", Toast.LENGTH_SHORT).show();
            }
        });
        passwordDialog.show(getFragmentManager(), null);

    }

    @Override
    public void faceResultFail(BaseBean response) {
        final SuccessDialog dialog = new SuccessDialog(this, response.getMessage());
        dialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dialog.cancel();
            }
        }.start();

        dismissLoadingDialog();
    }

    @Override
    public void getGetOrderIdSucc(GetOrderOpenidRes response) {
        if ("ghf".equals(chooseType)) {
            String url = Constant.SZ_URL +"?"+  response.getExtend();
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            bundle.putString(Constant.TITLE, "桂花分");
            RealNameActivity.mBActivity.finish();
            JumpUtils.jumptoNatvie(FaceAuthActivity.this, "webView", 0, bundle);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (resultCode) {
            case RESULT_OK:
                switchFragment(STATE_RESULT, intent);


                break;

            default:
                if (intent == null) {
                    intent = new Intent();
                }
                intent.putExtra(EXTRA_RESULT_CODE, resultCode);
                switchFragment(STATE_START, intent);
                break;
        }
        super.onActivityResult(requestCode, resultCode, intent);
    }

    public FaceAuthPresenter getmPresenter() {
        return mPresenter;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getCode() == MessageEvent.TO_SMRZ) {
//            mPresenter.faceResult();
        }
    }

    private void switchFragment(int state, Intent intent) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        switch (state) {
            case STATE_START:
                if (mStartPageFragment == null) {
                    mStartPageFragment = new StartPageFragment();
                }
                setFragmentArguments(mStartPageFragment, intent);
                transaction.replace(R.id.layout_top, mStartPageFragment);
                break;

            case STATE_RESULT:


                break;
            default:
                break;
        }
        if (mBottomButtonFragment == null) {
            mBottomButtonFragment = new BottomButtonFragment();
        }
        if (intent == null) {
            intent = new Intent();
        }
        intent.putExtra(BottomButtonFragment.EXTRA_STATE, state);
        setFragmentArguments(mBottomButtonFragment, intent);
        transaction.replace(R.id.layout_bottom, mBottomButtonFragment);
        transaction.commitAllowingStateLoss();
    }

    public static int getBitmapSize(Bitmap bitmap) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {    //API 19
            return bitmap.getAllocationByteCount();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {//API 12
            return bitmap.getByteCount();
        }
        // 在低版本中用一行的字节x高度
        return bitmap.getRowBytes() * bitmap.getHeight();
    }




    public String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }


    private void setFragmentArguments(Fragment fragment, Intent intent) {
        if (intent == null) {
            return;
        }
        Bundle extras = intent.getExtras();
        if (extras == null) {
            return;
        }
        if (fragment == null) {
            return;
        }
        if (fragment.getArguments() == null) {
            return;
        }
        fragment.getArguments().putAll(extras);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.face_start) {//                if (!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CAMERA)){
//                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},0);
//                }

            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CAMERA},
                        TAKE_PHOTO_REQUEST_CODE);
            } else {
            }
//
//                startActivityForResult(new Intent(FaceAuthActivity.this, SilentLivenessActivity.class), 0);
        }
    }

}
